'use strict';

const Service = require('./base');

class AuthService extends Service {
  async login(option) {
    const { ctx, app } = this;
    const { count, rows } = await this._findAll('Users', option);
    const userInfo = rows[0];
    if (count === 1) {
      return app.jwt.sign({
        id: userInfo.id,
        username: userInfo.username,
        password: userInfo.password,
      }, app.config.jwt.secret, { expiresIn: '12h' });
    }
    ctx.throw(403, '账号或密码错误');

  }

  async getUserInfo(token) {
    const { ctx } = this;
    const decoded = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);// 解密token
    return await this._findById('Users', decoded.id);
  }

  async getUserList() {
    return await this._findAll('Users', {
      attributes: {
        exclude: [ 'password' ],
      },
    });
  }
}

module.exports = AuthService;
